import Vue from 'vue'

import 'normalize.css/normalize.css' // A modern alternative to CSS resets

import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import LiYuUI from 'liyu-ui'
import '@/styles/index.scss' // global css

import App from './App'
import store from './store'
import router from './router'

import '@/icons' // icon
import '@/permission' // permission control

import Keycloak from 'keycloak-js'
import { obtain, load, search, submit } from './api/data'
/**
 * If you don't want to use mock-server
 * you want to use MockJs for mock api
 * you can execute: mockXHR()
 *
 * Currently MockJs will be used in the production environment,
 * please remove it before going online ! ! !
 */
if (process.env.NODE_ENV === 'production') {
  const { mockXHR } = require('../mock')
  mockXHR()
}
require('./mock')
// set ElementUI lang to EN
// Vue.use(ElementUI, { locale })
// 如果想要中文版 element-ui，按如下方式声明
Vue.use(ElementUI)
Vue.use(LiYuUI, { obtain, load, search, submit })
Vue.config.productionTip = false

// 可编辑表格插件
import 'xe-utils'
import XEUtils from 'xe-utils'
import VXETable from 'vxe-table'
import 'vxe-table/lib/index.css'
import zhCNLocat from 'vxe-table/lib/locale/lang/zh-CN'

VXETable.setup({
  i18n: (key, value) => XEUtils.get(zhCNLocat, key)
})
Vue.use(VXETable)
Vue.prototype.$XModal = VXETable.modal


// keycloak init options
const initOptions = {
  enable: process.env.VUE_APP_KEYCLOAK_OPTIONS_ENABLE,
  url: process.env.VUE_APP_KEYCLOAK_OPTIONS_URL,
  realm: process.env.VUE_APP_KEYCLOAK_OPTIONS_REALM,
  clientId: process.env.VUE_APP_KEYCLOAK_OPTIONS_CLIENTID,
  onLoad: process.env.VUE_APP_KEYCLOAK_OPTIONS_ONLOAD
}

if (initOptions.enable !== 'false') {
  const keycloak = Keycloak(initOptions)
  keycloak.init({ onLoad: initOptions.onLoad }).then(async authenticated => {
    if (!authenticated) {
      window.location.reload()
      return
    } else {
      Vue.prototype.$keycloak = keycloak
      await store.dispatch('user/keycloakLogin', keycloak.token)
      console.log('Authenticated', keycloak)
    }
    setInterval(() => {
      keycloak.updateToken(70).then((refreshed) => {
        if (refreshed) {
          console.log('Token refreshed')
        } else {
          console.log('Token not refreshed, valid for ' +
            Math.round(keycloak.tokenParsed.exp + keycloak.timeSkew - new Date().getTime() / 1000) + ' seconds')
        }
      }).catch(error => {
        console.log('Failed to refresh token', error)
      })
    }, 60000)
    new Vue({
      el: '#app',
      router,
      store,
      render: h => h(App)
    })
  }).catch(error => {
    console.log('Authenticated Failed', error)
  })
} else {
  new Vue({
    el: '#app',
    router,
    store,
    render: h => h(App)
  })
}
